#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <string>

void SetNoBlock(int fd) // 设置文件描述符为非阻塞
{
    int f1 = fcntl(fd, F_GETFL);
    if (f1 < 0)
    {
        perror("fcntl");
    }
    fcntl(fd, F_SETFL, fd | O_NONBLOCK);
}

int main()
{
    const std::string sep = "please input message# ";
    write(0, sep.c_str(), sep.size());
    char buffer[1024];
    while (true)
    {
        int n = read(0, buffer, sizeof(buffer) - 1);
        if (n == 0)
        {
            std::cout << "END OF FILE" << std::endl;
        }
        else if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "echo# " << buffer << std::endl;
        }
        else
        {
            if (errno == EAGAIN | errno = EWOULDBLOCK)
            {
                std::cout << "正在等待底层数据..." << std::endl;
                continue;
            }
            else if (errno == EINTR)
            {
                std::cout << "当前系统调用被信号中断" << std::endl;
                continue;
            }
            else
            {
                std::cout << "read error" << std::endl;
                return;
            }
        }
    }

    return 0;
}